package com.jiang.jetpackdemo.utils

import android.content.Context
import android.content.SharedPreferences
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 *
 * @ProjectName:    JetpackDemo
 * @ClassName:     SPUtil
 * @Description:     java类作用描述
 * @Author:         江
 * @CreateDate:     2020/4/3 15:38
 */
class SPUtil(private val context: Context) {
    companion object {
        const val SP_NAME = "SharedPreferences"
        const val KEY_VIDEO = "VideoRequestCache"
        const val KEY_VIDEO_DATE = "VideoRequestCacheData"
        const val KEY_NEWS_DATE = "NewsRequestCacheData"
        const val OOD_TIME: Long = 6 * 60 * 60 * 1000
    }

    private val sp: SharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE)
    private val editor: SharedPreferences.Editor = sp.edit()

    fun setVideoRequestCache(json: String) {
        GlobalScope.launch(Dispatchers.IO) {
            editor.putString(KEY_VIDEO, json)
            setVideoCacheData()
            editor.apply()
        }
    }

    fun getVideoRequestCache(callBack: CallBack) {
        GlobalScope.launch(Dispatchers.IO) {
            val cache = sp.getString(KEY_VIDEO, "") ?: ""
            GlobalScope.launch(Dispatchers.Main) {
                callBack.onFinish(cache)
            }
        }
    }

    suspend fun getVideoRequestCacheSuspend(): String {
        return withContext(Dispatchers.IO) {
            sp.getString(KEY_VIDEO, "") ?: ""
        }
    }

    private fun setVideoCacheData() {
        editor.putLong(KEY_VIDEO_DATE, System.currentTimeMillis())
    }

    fun setNewsCacheDate() {
        editor.putLong(KEY_VIDEO_DATE, System.currentTimeMillis())
        editor.apply()
    }

    fun isOutOfDate(key: String): Boolean {
        val date = sp.getLong(key, 0L)
        return if (0L == date) true else (System.currentTimeMillis() - date) >= OOD_TIME
    }

    interface CallBack {
        fun onFinish(cache: String)
    }
}